close[x]


PHP

PHP-Home PHP-Environment Setup PHP-Syntax PHP-Run PHP in XAMPP PHP-Variable PHP-Comment PHP-Datatype PHP-String PHP-Operators PHP-Decision PHP-loop PHP-Get/Post PHP-Do While loop PHP-While loop PHP-For loop PHP-Foreach loop PHP-Array PHP-Multidimensional Arrays PHP-Associative Arrays PHP-Indexed Arrays PHP-Function PHP-Cookies. PHP-Session PHP-File upload PHP-Email PHP-Data & Time PHP-Include & Require PHP-Error PHP-File I/O PHP-Read File PHP-Write File PHP-Append & Delete File PHP-Filter PHP-Form Validation PHP-MySQl PHP-XML PHP-AJAX



learncodehere.com



PHP - Cookies

PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user.

Cookie is created at server side and saved to client browser.

Each time the same computer requests a page with a browser, it will send the cookie too.

php cookie

With PHP, you can both create and retrieve cookie values.


PHP - Create Cookies

PHP provided setcookie() function to set a cookie.

This function requires upto six arguments and should be called before <html> tag

Syntax : Create Cookie


 setcookie(name, value, expire, path, domain, secure, httponly);

name : This sets the name of the cookie

Value : This sets the value of the named variable

expire:It is used to set the expiry timestamp of the cookie

path: It is used to specify the path on the server for which the cookie will be available.

domain: It is used to specify the domain for which the cookie is available.

security: It is used to indicate that the cookie should be sent only if a secure HTTPS connection exists.

Following example will create two cookies name and age these cookies will be expired after one hour.

Example : Create Cookie


 <?php 
 setcookie("name", "Will Smith", time()+3600, "/","", 0);
 setcookie("age", "36", time()+3600, "/", "",  0);   
 ?>



PHP - Checking Cookies

to check whether a cookie is set or not, the PHP isset() function is used.

Example : Checking Cookies


 <?php 
  if( isset($_COOKIE["name"]))
  echo "Name = " . $_COOKIE["name"] . "<br>";
else
  echo "Sorry... Not recognized" . "<br>";
?>

This will produce the following result −

Result


Name = Will Smith.

PHP - Accessing Cookies

For accessing a cookie value, the PHP $_COOKIE superglobal variable is used.

Example : Accessing Cookie


 <?php 
   echo "Name = " . $_COOKIE["name"] . "<br>";
  echo "Age = " . $_COOKIE["age"] . "<br>";   
 ?>

This will produce the following result −

Result


Name = Will Smith
Age = 36

PHP - Delete Cookie

To delete a cookie, use the setcookie() function with an expiration date in the past.

Example : Delete Cookie


  <?php 
  setcookie( "name", "", time()- 60, "/","", 0);
  setcookie( "age", "", time()- 60, "/","", 0);  
 ?>